export function getNowString() {
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1
  if (month < 10) month = '0' + month

  var date = now.getDate()
  if (date < 10) date = '0' + date

  var hours = now.getHours()
  if (hours < 10) hours = '0' + hours

  var minute = now.getMinutes()
  if (minute < 10) minute = '0' + minute

  var sec = now.getSeconds()
  if (sec < 10) sec = '0' + sec

  return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + sec
}

export function formateDateYMD(dateStr){
  return formatDate(dateStr,'yyyy月MM月dd日');
}

/**
 * 格式化日期
 */
export function formatDate(dateStr,pattern){
  
  if(typeof(dateStr) == undefined || dateStr == null ){
    return '';
  }

  if(dateStr.length != 19){
    return dateStr;
  }

    var date = new Date();
    //2023-12-01 03:12:54
    //首先转换成date对象
    date.setFullYear(dateStr.substring(0,4));
    var m = parseInt(dateStr.substring(5,7));
    date.setMonth(m-1);

    date.setDate(dateStr.substring(8,10));
    
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);

    if(typeof(pattern) == undefined || pattern == null || pattern == ''){
      pattern = "yyyy年MM月"
    }

    

    //开始格式化
    let o = {
      "M+" : date.getMonth()+1,                 //月份
      "d+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "S"  : date.getMilliseconds()             //毫秒
    };
    var yearExp = /(y+)/ ;
    var matchValue = null;
    if((matchValue = yearExp.exec(pattern)) != null) {      
      //console.log('matchValue='+matchValue[0])
      pattern=pattern.replace(matchValue[0], (date.getFullYear()+"").substring(4 - matchValue[0].length));
    }
    for(let k in o) {
      var regExp1 = new RegExp("("+ k +")");
      if((matchValue = regExp1.exec(pattern)) != null){        
        pattern = pattern.replace(matchValue[0], (matchValue[0].length==1) ? (o[k]) : (("00"+ o[k]).substring((""+ o[k]).length)));
      }
    }
    return pattern;
  
}


export function getYearMonth(v) {
  if (v && v.length > 7) {
    return v.substring(0, 7)
  } else {
    return ''
  }
}

export function getDate(v) {
  if (v && v.length > 10) {
    return v.substring(0, 10)
  } else {
    return ''
  }
}

/**
 * 计算两个日期相差几年
 */
export function getYearDiff(start,end){  
  var year =   Math.abs(new Date(end).getTime() - new Date(start).getTime())/(1000*3600*24*365)

  

  //格式化
  var result =  Number(year.toString().match(/^\d/));
  
  return result;
}